package J20241211_Stack;
import java.util.*;
/**
 * Created with IntelliJ IDEA.
 * Description: 栈——字符串解码
 * User: 王圆豪
 * Date: 2024-12-11
 * Time: 21:51
 */


public class Solution {
    public static void main(String[] args) {
        System.out.println(decodeString("3[a]2[bc]"));
    }
    public static String decodeString(String s) {
        int count = 0;
        char[] arr = s.toCharArray();
        int i = 0;
        Stack<String> s1  = new Stack<>();
        Stack<Integer> s2  = new Stack<>();
        s1.push("");
        s2.push(1);
        while(i < s.length()){
            char ch = arr[i];
            if(ch >= '0' && ch <= '9'){
                int tmp = ch - '0';
                i++;
                while(arr[i] >= '0' && arr[i] <= '9'){
                    tmp = tmp*10 + (arr[i++]-'0');
                }
                s2.push(tmp);
            }else if(ch == '['){
                i++;
                StringBuffer tmp = new StringBuffer();
                while(arr[i] >= 'a' && arr[i] <= 'z'){
                    tmp.append(arr[i++]);
                }
                s1.push(tmp.toString());
            }else if(ch == ']'){
                int k = s2.pop();
                StringBuffer tmp = new StringBuffer();
                String p = s1.pop();
                tmp.append(s1.pop());
                while(k-- != 0){
                    tmp.append(p);
                }
                s1.push(tmp.toString());
                i++;
            }else{
                StringBuffer tmp = new StringBuffer();
                tmp.append(s1.pop());
                while(i < arr.length && arr[i] >= 'a' && arr[i] <= 'z'){
                    tmp.append(arr[i++]);
                }
                s1.push(tmp.toString());
            }
        }
        return s1.pop();
    }
}
